<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import type { SearchStuModel, StuModel, StuModelArray, ClazzModelArray } from '@/api/model/model'
import { queryStuList } from '@/api/stu/index'
import { queryAllApi as queryAllClazzApi } from '@/api/clazz/index'
import { addStu, updateStu, deleteStuByIds, queryAllEmpApi, getStuById, violationController } from '@/api/stu/index'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
const formLabelWidth = "80px";
const searchForm = ref<SearchStuModel>({
  name: '',
  degree: '',
  clazzId: ''
})
const stuList = ref<StuModelArray>()

const query = async () => {
  console.log(searchForm.value);
  const res = await queryStuList(searchForm.value.name, searchForm.value.degree, searchForm.value.clazzId, currentPage.value, pageSize.value);
  stuList.value = res.data.rows;
  total.value = res.data.total;
}
const clear = () => {
  searchForm.value = {
    name: '',
    degree: '',
    clazzId: ''
  }
}
//所有的班级数据
let clazzs = ref<ClazzModelArray>([])
//加载所有的班级数据
const queryAllClazz = async () => {
  let result = await queryAllClazzApi()
  if (result.code) {
    clazzs.value = result.data
  }
}
const genderList = [
  { id: 1, name: "男" },
  { id: 2, name: "女" },
]
const degreeList = [
  { id: 1, name: "初中" },
  { id: 2, name: "高中" },
  { id: 3, name: "大专" },
  { id: 4, name: "本科" },
  { id: 5, name: "硕士" }
]
onMounted(() => {
  query();
  queryAllClazz()
});
// 分页的数据
const currentPage = ref<number>(1)
const pageSize = ref<number>(5);
const total = ref<number>(0);
const handleSizeChange = () => {
  query();
}
const handleCurrentChange = () => {
  query();
}

//新增学员
let formTitle = ref<string>('') //表单的标题
let stu = ref<StuModel>({ //学生对象-表单数据绑定
  name: '',
  no: '',
  gender: '',
  phone: '',
  idCard: '',
  isCollege: '',
  address: '',
  degree: '',
  graduationDate: '',
  clazzId: ''
})
//清空表单
const clearStu = () => {
  stu.value = {
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: ''
  }
}
const openAddDialog = () => {
  dialogFormVisible.value = true
  formTitle.value = '新增学员'
  clearStu()
}
// 更新
const openUpdateDialog = async (idx: number, row: StuModel) => {
  // 展示弹框
  dialogFormVisible.value = true;
  formTitle.value = "修改班级";
  // 回显查询，参数是id
  const res = await getStuById(row.id!);
  stu.value = res.data;
}

//保存按钮
const doAddOrUpdate = (formEL: FormInstance | undefined) => {
  // console.log("insertOrUpdate");
  if (!formEL) {
    return;
  }
  // 先校验表单的格式
  formEL.validate(async (valid) => {
    if (valid) {
      // 校验通过
      let res = null;
      let insertFlag = null;
      if (stu.value.id) {//修改
        insertFlag = false;
        res = await updateStu(stu.value);
      } else {// 新增
        insertFlag = true;
        res = await addStu(stu.value);
      }
      if (!res.code) {
        ElMessage.error(res.msg);
      } else {
        // 隐藏dialog
        dialogFormVisible.value = false;
        // 清空dialog，通过dialog的回调统一处理
        ElMessage({ type: 'success', message: insertFlag ? '添加成功' : '修改成功', })
        query();
      }
    }
  });
}
//dialog弹窗
const dialogFormVisible = ref<boolean>(false)
//表单校验
const rules = ref<FormRules<StuModel>>({
  name: [
    { required: true, message: '姓名为必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '班级名称长度在2-20个字之间', trigger: 'blur' },
  ],
  no: [
    { required: true, message: '学号为必填项', trigger: 'blur' },
    { min: 10, max: 10, message: '学号长度为10个字', trigger: 'blur' },
  ],
  gender: [
    { required: true, message: '性别为必填项', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '手机号为必填项', trigger: 'blur' },
    { pattern: /^1[3-9][0-9]{9}$/, message: '手机号格式有误', trigger: 'blur' },
  ],
  idCard: [
    { required: true, message: '身份证号为必填项', trigger: 'blur' },
    { min: 18, max: 18, message: '请输入合法的身份证号', trigger: 'blur' },
  ],
  isCollege: [
    { required: true, message: '是否院校为必填项', trigger: 'blur' }
  ]
})
const dialogFromRef = ref<FormInstance>();
//关闭时自动回调
function dialogClose() {
  stu.value =
  {
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: ''
  }
  // 重置form校验规则
  // formRef.value.resetFields();
}
const handleDelete = (idx: number, row: StuModel) => {
  ElMessageBox.confirm(
    '您确认删除此数据吗?',
    '确认删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    // 发删除请求
    const res = await deleteStuByIds('' + row.id);
    if (!res.code) {
      ElMessage({ type: 'error', message: res.msg, })
    } else {
      ElMessage({ type: 'success', message: '删除成功' })
      // 刷新页面
      query();
    }
  })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
// 保存所有选中的行的id
const selectIds = ref<string[]>([])
// 入参：是所有的选中的行的数据的数组
const handleSelectionChange = (rows: StuModelArray) => {
  if (!rows || rows.length <= 0) {
    selectIds.value = []
  } else {
    for (let i = 0; i < rows.length; i++) {
      selectIds.value.push(rows[i].id!);
    }
  }
}
const batchDelete = () => {
  // 先判断seleectIds是否有值
  if (!selectIds.value || selectIds.value.length <= 0) {
    ElMessage({ type: 'error', message: '没有选中任何数据' })
    return;
  }
  ElMessageBox.confirm('您确认删除这些数据吗?', '确认删除', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', })
    .then(async () => {
      // 发删除请求
      const res = await deleteStuByIds("" + selectIds.value);
      if (!res.code) {
        ElMessage({ type: 'error', message: res.msg, })
      } else {
        ElMessage({ type: 'success', message: '删除成功' })
        // 刷新页面
        query();
        // 重置selectIds
        selectIds.value = []
      }
    }).catch(() => {
      ElMessage({ type: 'info', message: '取消删除' })
    })
}
//违纪
const open = (idx: number, row: StuModel) => {
  ElMessageBox.prompt('请输入违纪扣分', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern:
      /^(25[0-5]|2[0-4]\d|1\d{2}|0?\d{1,2})$/,
    inputErrorMessage: '请输入0-255的数字',
  })
    .then(async ({ value }) => {
      // 发违纪请求
      const res = await violationController(row.id, value);
      if (!res.code) {
        ElMessage({ type: 'error', message: res.msg, })
      } else {
        ElMessage({ type: 'success', message: '操作成功' })
        // 刷新页面
        query();
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}
</script>

<template>
  <span class="title">学员管理 </span>
  <!----------------------------------搜索框-------------------------------------->
  <el-form :inline="true" :model="searchForm" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchForm.name" placeholder="请输入员工姓名" style="width:200px" clearable />
    </el-form-item>
    <el-form-item label="学历">
      <el-select v-model="searchForm.degree" placeholder="请选择" style="width:200px" clearable>
        <el-option label="初中" value="1" />
        <el-option label="高中" value="2" />
        <el-option label="大专" value="3" />
        <el-option label="本科" value="4" />
        <el-option label="硕士" value="5" />
        <el-option label="博士" value="6" />
      </el-select>
    </el-form-item>
    <el-form-item label="所属班级">
      <el-select v-model="searchForm.clazzId" placeholder="请选择" style="width:200px" clearable>
        <el-option v-for="clazz in clazzs" :label="clazz.name" :value="clazz.id" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="query">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
  <el-button type="primary" @click="openAddDialog">+ 新增员工</el-button>
  <el-button type="danger" @click="batchDelete">- 批量删除</el-button>

  <!-----------------------页面主体的数据列表-------------------------------->
  <el-table :data="stuList" border style="width: 100%; margin-top:10px" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="30" />
    <el-table-column prop="name" label="姓名" width="100" align="center" />
    <el-table-column prop="no" label="学号" width="130" align="center" />
    <el-table-column prop="clazzName" label="班级" width="160" align="center" />
    <el-table-column prop="gender" label="性别" width="60" align="center">
      <template #default="scope">
        <span v-if="scope.row.gender == 1">男</span>
        <span v-else-if="scope.row.gender == 2">女</span>
        <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="140" align="center" />
    <el-table-column prop="degree" label="最高学历" width="90" align="center">
      <template #default="scope">
        <span v-if="scope.row.degree == 1">初中</span>
        <span v-else-if="scope.row.degree == 2">高中</span>
        <span v-else-if="scope.row.degree == 3">大专</span>
        <span v-else-if="scope.row.degree == 4">本科</span>
        <span v-else-if="scope.row.degree == 5">硕士</span>
        <span v-else-if="scope.row.degree == 6">博士</span>
        <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column prop="violationCount" label="违纪次数" width="70" align="center" />
    <el-table-column prop="violationScore" label="违纪扣分" width="70" align="center" />
    <el-table-column prop="updateTime" label="最后修改时间" width="180" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="openUpdateDialog(scope.$index, scope.row)">编辑</el-button>
        <el-button @click="open(scope.$index, scope.row)" size="small" type="warning">违纪</el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!----------------------------------分页组件---------------------------------------->
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30, 40]"
    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
    @current-change="handleCurrentChange" style="margin-top:10px" />
  <!-- 新增/修改学员对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="formTitle" width="700" @close="dialogClose">
    <el-form :model="stu" ref="dialogFromRef" :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
            <el-input v-model="stu.name" placeholder="请输入学员姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" :label-width="formLabelWidth" prop="no">
            <el-input v-model="stu.no" placeholder="请输入学员学号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-select v-model="stu.gender" placeholder="请选择" style="width: 100%">
              <el-option :label="gender.name" :value="gender.id" v-for="(gender, index) in genderList"
                :key="gender.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
            <el-input v-model="stu.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="身份证号" :label-width="formLabelWidth" prop="idCard">
            <el-input v-model="stu.idCard" placeholder="请输入身份证号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校" :label-width="formLabelWidth" prop="isCollege">
            <el-select v-model="stu.isCollege" placeholder="请选择" style="width: 100%;">
              <el-option label="是" value="1" />
              <el-option label="否" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="联系地址" :label-width="formLabelWidth">
            <el-input v-model="stu.address" placeholder="请输入联系地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历" :label-width="formLabelWidth">
            <el-select v-model="stu.degree" placeholder="请选择" style="width: 100%">
              <el-option :label="degree.name" :value="degree.id" v-for="(degree, index) in degreeList"
                :key="degree.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="毕业时间" :label-width="formLabelWidth">
            <el-date-picker v-model="stu.graduationDate" type="date" placeholder="请选择毕业时间" value-format="YYYY-MM-DD"
              style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级" :label-width="formLabelWidth">
            <el-select v-model="stu.clazzId" placeholder="请选择" style="width: 100%;">
              <el-option v-for="clazz in clazzs" :label="clazz.name" :value="clazz.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="doAddOrUpdate(dialogFromRef)">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scope>
.title {
  font-size: 20px;
  font-weight: 600;
}

.demo-form-inline {
  margin-top: 10px
}
</style>